package com.itwmk.controller;

import com.itwmk.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * @author wmk
 */
@Slf4j
@RestController
@RequestMapping("common")
public class CommonController {
    @Value("${img.path}")
    private String basePath;
    /**
     * 上传图片功能
     * 参数file要与前端name名一致
     * file是一个临时文件
     * @param file
     * @return
     */
    @PostMapping("upload")
    public R<String> uploadImg(MultipartFile file){
        //获取图片原始名
        String filename = file.getOriginalFilename();
        //获取后缀.xxx
        String suffix = filename.substring(filename.lastIndexOf("."));
        //用UUID重新随机生成文件名，防文件名重复被覆盖
        String newFileName= UUID.randomUUID()+suffix;
        log.info("filename:{}",newFileName);
        try {
            //将临时文件转存
            file.transferTo(new File(basePath + newFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(newFileName);
    }

    /**
     * 图片回填
     * @param name
     * @param response
     */
    @GetMapping("download")
    public void downloadImg(String name, HttpServletResponse response){
        try {
            if (!new File(basePath+name).exists()){
                return;
            }
            FileInputStream inputStream = new FileInputStream(basePath+name);


            ServletOutputStream outputStream = response.getOutputStream();
            int len=0;
            byte[] bytes = new byte[1024];
            while ((len=inputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            inputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
